#ifndef camera_h
#define camera_h

#include "./screen.h" // 引入 screen_draw_jpeg
#include "../logger.h"
#include "esp_camera.h"
#include <Wire.h>

// #define CAMERA_MODEL_AI_THINKER
// 定义引脚
#ifndef CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM     17
#define RESET_GPIO_NUM    26

#define XCLK_GPIO_NUM     14
#define PCLK_GPIO_NUM     22

// config.pin_sccb_sda = SIOD_GPIO_NUM;
// config.pin_sccb_scl = SIOC_GPIO_NUM;
#define SIOD_GPIO_NUM     23
#define SIOC_GPIO_NUM     18

#define VSYNC_GPIO_NUM    21
#define HREF_GPIO_NUM     27

#define D0_GPIO_NUM       34
#define D1_GPIO_NUM       33
#define D2_GPIO_NUM       25
#define D3_GPIO_NUM       35
#define D4_GPIO_NUM       39
#define D5_GPIO_NUM       38
#define D6_GPIO_NUM       37
#define D7_GPIO_NUM       36
#else
#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27

#define D7_GPIO_NUM       35
#define D6_GPIO_NUM       34
#define D5_GPIO_NUM       39
#define D4_GPIO_NUM       36
#define D3_GPIO_NUM       21
#define D2_GPIO_NUM       19
#define D1_GPIO_NUM       18
#define D0_GPIO_NUM        5

#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22
#endif

bool camera_ok = false;
camera_fb_t *fb = NULL;
void check_camera_i2c(){ 
    Wire.begin(SIOD_GPIO_NUM, SIOC_GPIO_NUM);
    Wire.setClock(100000);        // 设置I2C时钟频率为100kHz
    Wire.beginTransmission(0x30); // 0x30是常见的摄像头I2C地址
    if (Wire.endTransmission() == 0) {
        logln("0x30 I2C communication OK");
    } else {
        logln("0x30 I2C communication failed");
    }
}

void check_probe_i2c(){ 
    Wire.begin(SIOD_GPIO_NUM, SIOC_GPIO_NUM);
    Wire.setClock(1000000);        // 设置I2C时钟频率为100kHz
    Wire.beginTransmission(0x1A); // 海曼I2C地址
    if (Wire.endTransmission() == 0) {
        logln("0x1A I2C communication OK");
    } else {
        logln("0x1A I2C communication failed");
    }
}
// 摄像头初始化
void camera_init()
{
    pinMode(PIN_I2C_VDD, OUTPUT);
    digitalWrite(PIN_I2C_VDD, LOW);
    check_camera_i2c(); // 检查 I2C 通信
    check_probe_i2c();
    camera_config_t config;
    config.ledc_channel = LEDC_CHANNEL_0;
    config.ledc_timer = LEDC_TIMER_0;
    config.pin_d0 = D0_GPIO_NUM;
    config.pin_d1 = D1_GPIO_NUM;
    config.pin_d2 = D2_GPIO_NUM;
    config.pin_d3 = D3_GPIO_NUM;
    config.pin_d4 = D4_GPIO_NUM;
    config.pin_d5 = D5_GPIO_NUM;
    config.pin_d6 = D6_GPIO_NUM;
    config.pin_d7 = D7_GPIO_NUM;
    config.pin_xclk = XCLK_GPIO_NUM;
    config.pin_pclk = PCLK_GPIO_NUM;
    config.pin_vsync = VSYNC_GPIO_NUM;
    config.pin_href = HREF_GPIO_NUM;
    config.pin_sccb_sda = SIOD_GPIO_NUM;
    config.pin_sccb_scl = SIOC_GPIO_NUM;
    config.pin_pwdn = PWDN_GPIO_NUM;
    config.pin_reset = RESET_GPIO_NUM;
    config.xclk_freq_hz = 20000000;
    config.frame_size = FRAMESIZE_QVGA;
    config.pixel_format = PIXFORMAT_JPEG; // for streaming
    // config.pixel_format = PIXFORMAT_RGB565; // for face detection/recognition
    config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
    config.fb_location = CAMERA_FB_IN_PSRAM;
    config.jpeg_quality = 12;
    config.fb_count = 1;

    if (config.pixel_format == PIXFORMAT_JPEG)
    {
        if (psramFound())
        {
            logf("PSRAM found, using it for camera buffers\n");
            config.jpeg_quality = 10;
            config.fb_count = 2;
            config.grab_mode = CAMERA_GRAB_LATEST;
        }
        else
        {   
            logf("PSRAM not found\n");
            config.frame_size = FRAMESIZE_SVGA;
            config.fb_location = CAMERA_FB_IN_DRAM;
        }
    }
    else
    {
        config.frame_size = FRAMESIZE_240X240;
    }

    // camera init
    logln("Initializing camera...");
    
    esp_err_t err = esp_camera_init(&config);
    if (err != ESP_OK)
    {
        logf("Camera init failed with error 0x%x", err);
        camera_ok = false;
        return;
    }
    camera_ok = true;
    logf("Camera init okay");
    sensor_t *s = esp_camera_sensor_get();
    if (s->id.PID == OV3660_PID)
    {
        s->set_vflip(s, 1);       // flip it back
        s->set_brightness(s, 1);  // up the brightness just a bit
        s->set_saturation(s, -2); // lower the saturation
    }
    if (config.pixel_format == PIXFORMAT_JPEG)
    {
        s->set_framesize(s, FRAMESIZE_QVGA);
    }

}

// 摄像头功能：抓取帧并显示到屏幕
void camera_loop()
{ 
    if (! camera_ok) {
        logln("Camera not initialized, retrying...");
        camera_init();
        delay(1000);
        return;
    }
    fb = esp_camera_fb_get();
    if (!fb) {
        logln("Camera capture failed");
        esp_camera_fb_return(fb);
        fb = NULL;
        delay(10);
        return;
    }

    // 仅处理 JPEG 格式（camera_init 中设置为 PIXFORMAT_JPEG）
    if (fb->format == PIXFORMAT_JPEG) {
        // 将 JPEG 数据交给屏幕绘制函数
        // screen_draw_jpeg(fb->buf, fb->len);
        screen_draw_cropped_jpeg(fb->buf, fb->len);
    } else {
        // 如果是其它格式，可以在此添加转换/显示逻辑
        logln("Non-JPEG frame received");
    }
    // 释放帧缓冲
    esp_camera_fb_return(fb);
    fb = NULL;
}


#endif
